package edu.cibertec.sicsolutions.vfs.votacion.action;

import java.sql.Time;
import java.sql.Timestamp;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import edu.cibertec.sicsolutions.constants.Constants;
import edu.cibertec.sicsolutions.constants.SessionConstants;
import edu.cibertec.sicsolutions.exception.DomainException;
import edu.cibertec.sicsolutions.parameters.ParamerterVfs;
import edu.cibertec.sicsolutions.util.DateUtil;
import edu.cibertec.sicsolutions.util.StringUtil;
import edu.cibertec.sicsolutions.vfs.domain.votacion.ElectorVirtual;
import edu.cibertec.sicsolutions.vfs.domain.votacion.MesaVotacion;
import edu.cibertec.sicsolutions.vfs.domain.votacion.Parametros;
import edu.cibertec.sicsolutions.vfs.domain.votacion.SessionTracking;
import edu.cibertec.sicsolutions.vfs.service.ElectorVirtualService;
import edu.cibertec.sicsolutions.vfs.service.MesaVotacionService;
import edu.cibertec.sicsolutions.vfs.service.ParametrosService;
import edu.cibertec.sicsolutions.vfs.service.SessionTrackingService;

public class IdentificacionAction  extends  DispatchAction{
	
	private static final Logger log = Logger.getLogger(IdentificacionAction.class);
	ServletContext servletContext = null;
	Timestamp fechaInicio = null;
	Timestamp fechaFinal = null;
	
  	 public ActionForward init(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
  		 
  	 
	  return mapping.findForward("noLogin");
	}
	 
	 public ActionForward logout(ActionMapping mapping, ActionForm form,
				HttpServletRequest request, HttpServletResponse response)
				throws Exception { 
		  HttpSession session = request.getSession();
		  ElectorVirtual electorVirtual = (ElectorVirtual)session.getAttribute(SessionConstants.ELECTOR); 
		  if(electorVirtual!=null){ 
			 ParamerterVfs.idElector = electorVirtual.getLogin(); 
		     session.invalidate();
		  }
	 	  return init(mapping, form, request, response);
	}
	
	 public ActionForward identificarElector(ActionMapping mapping, ActionForm form,
				HttpServletRequest request, HttpServletResponse response)
				throws Exception {
	  log.info("begin method identificarElector()");
	  try {
			Parametros parametro = new Parametros();
		  	parametro.setId(1);
		  	fechaInicio =  Timestamp.valueOf(ParametrosService.getParametrosByPk(parametro).getValor() );	 
		  	parametro.setId(2);
		  	fechaFinal =  Timestamp.valueOf(ParametrosService.getParametrosByPk(parametro).getValor() );
	   	
		  
         if(fechaInicio.after(DateUtil.getTimestampNow())  ){
        	 request.getSession().setAttribute("msjLogin", "Espere a que se inicie la votacion");
        	 return init(mapping, form, request, response);
         }
         if(DateUtil.getTimestampNow().after(fechaFinal )  ){
        	 request.getSession().setAttribute("msjLogin", "La votacion ya termino");
        	 return init(mapping, form, request, response);
         }
		 ElectorVirtual electorVirtual0 = new ElectorVirtual();
		 electorVirtual0.setLogin( request.getParameter("user")) ;
		 electorVirtual0.setPassword(request.getParameter("password"));
		 ElectorVirtual[] electorVirtuals= ElectorVirtualService.findElectorVirtualByClass(electorVirtual0);
		 if(electorVirtuals!=null && electorVirtuals.length > 0){
			  servletContext = this.getServlet().getServletContext();
			  ParamerterVfs.servletContext = servletContext;
	 			ElectorVirtual electorVirtual =  electorVirtuals[0];
				if( electorVirtual!=null){
					if(electorVirtual.getFlagVotar().equals(1)){
						request.getSession().setAttribute("msjLogin", "Ud. ya realizo su voto.");
						return init(mapping, form, request, response);
					}
					
					MesaVotacion mesaVotacion = MesaVotacionService.getMesaVotacionByPk(new MesaVotacion(electorVirtual.getEmpadronado().getCodigoMesa()));
					 if(mesaVotacion!=null){
					    if(mesaVotacion.getConsulado()!=null){
					    	if(mesaVotacion.getConsulado().getFlagEstadoVotacion() ==0){
					    		request.getSession().setAttribute("msjLogin", "Ya se cerro la votacion");
								return init(mapping, form, request, response);
					    	}
					    }	 
					 } 
					 
					
					
				 	synchronized (servletContext) { 
				             if(servletContext.getAttribute(electorVirtual0.getLogin())==null  ){
				            	 if(!request.getSession().isNew()){
				            		 request.getSession().invalidate();
				            	 }
				            	 HttpSession session = request.getSession(true);
				            	 session.setAttribute(SessionConstants.ELECTOR,electorVirtual);
				            	 
				            	 SessionTracking sessionTracking = new SessionTracking();
				         		 sessionTracking.setSessionId(session.getId()); 
				         		 sessionTracking.setCodigoMesaVotacion(electorVirtual.getEmpadronado().getCodigoMesa());
				         		 try {
				         				SessionTrackingService.insertSessionTracking(sessionTracking);
				         		 } catch (DomainException e) {
				         				log.error(null,e);
				         		 }
				         		 
				            	 ParamerterVfs.idElector = electorVirtual.getLogin(); 
				            	 servletContext.setAttribute(electorVirtual.getLogin(),electorVirtual  );
				            	 return mapping.findForward(Constants.SUCCESS_INIT) ;
				              }  
				             else {
				            	 request.getSession().setAttribute("msjLogin", "Ud. ya se encuentra votando");
				             }
					}  
				}
		  } 
		 else{
		    request.getSession().setAttribute("msjLogin", "Ud. no esta registrado para votar");	 
		 }
		
		} catch (Exception e) {
		     log.error(null,e);
		}
		log.info("end method identificarElector()");
		return init(mapping, form, request, response);
	 }
	 

}
